package com.top.mall.main.order

import android.os.Bundle
import androidx.lifecycle.LifecycleOwner
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.view.OptionsPickerView
import com.blankj.utilcode.util.*
import com.module.lemlin.http.Status
import com.module.lemlin.owner.OwnerViewModeActivity
import com.top.mall.R
import com.top.mall.custom.setTransitionStatus
import com.top.mall.entity.SettlementCart
import com.top.mall.entity.UserInvoice
import com.top.mall.jetpack.vm.OrderViewModel
import com.top.mall.main.order.adapter.OrderGoodsAdapter
import kotlinx.android.synthetic.main.activity_order_settlement.*
import kotlinx.android.synthetic.main.include_order_expense.*
import kotlinx.android.synthetic.main.include_order_goods.*
import kotlinx.android.synthetic.main.include_order_user.*
import java.util.*

class OrderSettlementActivity : OwnerViewModeActivity<OrderViewModel>() {

    companion object {
        private const val KEY_SETTLEMENT_CART = "KEY_SETTLEMENT_CART"
        fun open(settlementCart: SettlementCart) {
            val bundle = Bundle().apply {
                putSerializable(KEY_SETTLEMENT_CART, settlementCart)
            }
            ActivityUtils.startActivity(bundle, OrderSettlementActivity::class.java)
        }
    }

    private var mUserInvoice: UserInvoice? = null

    private val mOptions: OptionsPickerView<String> by lazy {
        OptionsPickerBuilder(this) { options1, option2, options3, v ->
            val data = viewModel.userInvoiceLiveData.value?.data?.data
                ?: return@OptionsPickerBuilder
            mUserInvoice = data[options1]
            tvOrderSettlementFapiao.text = mUserInvoice?.company_name
        }.build()
    }

    private var mDeliveryTime: Long? = null

    private val mOptionsTime: OptionsPickerView<String> by lazy {
        OptionsPickerBuilder(this) { options1, option2, options3, v ->
            val data = viewModel.userDeliveryListLiveData.value?.data?.data
                ?: return@OptionsPickerBuilder
            val day = data[options1]
            val time = day.list[option2]
            tvOrderUser4.text = "${day.name} ${time.time}:00"
            mDeliveryTime = test(day.day, time.time.toInt()) / 1000
        }.build()
    }

    private fun test(day: Int, time: Int): Long {
        val cal = Calendar.getInstance()
        cal.add(Calendar.DAY_OF_YEAR, day)
        cal.set(Calendar.HOUR_OF_DAY, time)
        cal.set(Calendar.SECOND, 0)
        cal.set(Calendar.MINUTE, 0)
        cal.set(Calendar.MILLISECOND, 0)
        return cal.timeInMillis
    }

    private val mSettlementCart: SettlementCart?
        get() = intent?.extras?.getSerializable(KEY_SETTLEMENT_CART) as? SettlementCart

    override fun viewModel(): OrderViewModel {
        return createViewModel()
    }

    override val layoutResId: Int
        get() = R.layout.activity_order_settlement

    override fun stateBar(): StatusBar {
        return StatusBar(view = flOrderSettleBar)
    }

    override fun initView() {

        imageViewBack.setOnClickListener { finish() }
        //设置状态栏颜色
        BarUtils.setStatusBarLightMode(this, false)

        tvOrderSettlementFapiao.setOnClickListener {
            viewModel.userInvoice()
        }

        tvOrderUser4.setOnClickListener {
            viewModel.userDeliveryTime()
        }

        tvOrderSettlementSubmit.setOnClickListener {

            viewModel.orderSubmit(
                address_id = mSettlementCart?.address?.id,
                recipient_id = mSettlementCart?.recipient?.id,
                delivery_time = mDeliveryTime,
                user_note = tvOrderSettlementBeizhu.text.toString(),
                cartList = mSettlementCart?.cart_list?.map { it.cart_id }?.toTypedArray()
                    ?: arrayOf(),
                invoice_id = mUserInvoice?.id
            )
        }
    }

    override fun initData() {
        mSettlementCart?.let { fillData(it) }
    }

    override fun initViewMode() {
        viewModel.userInvoiceLiveData.observe(this as LifecycleOwner, { response ->
            this.setTransitionStatus(response)
            if (response.status != Status.SUCCESS) {
                return@observe
            }
            val data = response.data?.data ?: return@observe

            mOptions.setPicker(data.map { it.company_name })
            mOptions.show()
        })
        viewModel.orderSubmitLiveData.observe(this as LifecycleOwner, { response ->
            this.setTransitionStatus(response)
            if (response.status != Status.SUCCESS) {
                return@observe
            }
            val data = response.data?.data
                ?: return@observe
            OrderPaymentActivity.open(data.order_id.toInt())
            finish()
        })
        viewModel.userDeliveryListLiveData.observe(this as LifecycleOwner, { response ->
            this.setTransitionStatus(response)
            if (response.status != Status.SUCCESS) {
                return@observe
            }
            val data = response.data?.data
                ?: return@observe
            mOptionsTime.setPicker(
                data.map { it.name },
                data.map { it.list.map { "${it.time}:00配送费返还${it.return_money}%" } })
            mOptionsTime.show()
        })
    }

    private fun fillData(settlementCart: SettlementCart) {
        tvOrderUser1.text = settlementCart.address.full_address
        tvOrderUser2.text =
            "${settlementCart.recipient.surname}${settlementCart.recipient.user_name}"
        tvOrderUser3.text = settlementCart.recipient.mobile

        rvOrderGoodsBody.adapter =
            OrderGoodsAdapter().apply {
                setNewInstance(settlementCart.cart_list)
            }

        tvOrderExpense1.text =
            if (settlementCart.coupon_list.size > 0) "可用${settlementCart.coupon_list.size}优惠券" else "暂无可用优惠券"
        tvOrderExpense2.text = "￥${settlementCart.goods_fee}"
        tvOrderExpense3.text = "￥${settlementCart.shipping_price}"
        tvOrderExpense5.text =
            "￥${settlementCart.goods_fee.toDouble() + settlementCart.shipping_price.toDouble()}"

        tvOrderSettlementPrice.text =
            "￥${settlementCart.goods_fee.toDouble() + settlementCart.shipping_price.toDouble()}"

    }
}